package com.wu.demo.farmework.manager;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wu.demo.common.Constants;
import com.wu.demo.common.domain.LoginUser;
import com.wu.demo.common.redis.RedisCache;
import com.wu.demo.common.utils.IdUtils;
import com.wu.demo.common.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 */
@Component
public class TokenManager {


    // 令牌秘钥
    private String secret = "aP7T2qoZC+XoJqFIr5CS1A==";

    // 令牌有效期（默认30分钟）
    private int expireTime = 300;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    public Long getLoginUserId(){
        LoginUser loginUser = getLoginUser(ServletUtils.getRequest());
        if(loginUser != null){
            return loginUser.getUser().getUserId();
        }
        return null;
    }

    public String getLoginUserName(){
        LoginUser loginUser = getLoginUser(ServletUtils.getRequest());
        if(loginUser != null){
            return loginUser.getUser().getUserName();
        }
        return null;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (!StringUtils.isBlank(token)) {
            String userKey = getTokenKey(token);
            LoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (ObjectUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken().trim())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public LoginUser createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        refreshToken(loginUser);
        return loginUser;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }


    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        return token;
    }

    private String getTokenKey(String token) {
        return Constants.WHOUSE_LOGIN_TOKEN_KEY + token;
    }
}
